<!-- 消息编辑对话框 -->
<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
import type { ChatMessage } from '../stores/ai'
import { MdEditor, type ToolbarNames } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

const props = defineProps<{
  modelValue: boolean
  message: ChatMessage | null
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'save': [content: string]
}>()

const content = ref('')
const isMaximized = ref(false)
const dialogRef = ref<HTMLElement | null>(null)

// 窗口位置和大小
const windowState = ref({
  x: window.innerWidth * 0.1,
  y: window.innerHeight * 0.1,
  width: window.innerWidth * 0.8,
  height: window.innerHeight * 0.8,
  // 保存最大化前的状态
  beforeMaximize: null as null | { x: number; y: number; width: number; height: number }
})

// 编辑器配置
const editorConfig = computed(() => ({
  toolbars: [
    'bold', 'italic', 'strikethrough', '|',
    'title', 'quote', 'unorderedList', 'orderedList', '|',
    'codeRow', 'code', 'link', 'image', '|',
    'preview', 'fullscreen'
  ] as ToolbarNames[],
  toolbarsExclude: [] as ToolbarNames[],
  preview: true,
  language: 'zh-CN',
  theme: 'dark'
}))

// 计算窗口样式
const dialogStyle = computed(() => ({
  transform: isMaximized.value ? 'none' : `translate(${windowState.value.x}px, ${windowState.value.y}px)`,
  width: isMaximized.value ? '100%' : `${windowState.value.width}px`,
  height: isMaximized.value ? '100%' : `${windowState.value.height}px`,
  transition: 'all 0.3s ease-out'
}))

// 处理窗口拖动
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

const startDrag = (e: MouseEvent) => {
  if (isMaximized.value) return
  isDragging.value = true
  dragOffset.value = {
    x: e.clientX - windowState.value.x,
    y: e.clientY - windowState.value.y
  }
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}

const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return
  windowState.value.x = e.clientX - dragOffset.value.x
  windowState.value.y = e.clientY - dragOffset.value.y
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 处理窗口大小调整
const isResizing = ref(false)
const resizeEdge = ref<string | null>(null)
const resizeStartPos = ref({ x: 0, y: 0 })
const resizeStartDims = ref({ width: 0, height: 0 })

const startResize = (e: MouseEvent, edge: string) => {
  if (isMaximized.value) return
  isResizing.value = true
  resizeEdge.value = edge
  resizeStartPos.value = { x: e.clientX, y: e.clientY }
  resizeStartDims.value = {
    width: windowState.value.width,
    height: windowState.value.height
  }
  document.addEventListener('mousemove', onResize)
  document.addEventListener('mouseup', stopResize)
}

const onResize = (e: MouseEvent) => {
  if (!isResizing.value) return
  const dx = e.clientX - resizeStartPos.value.x
  const dy = e.clientY - resizeStartPos.value.y

  if (resizeEdge.value?.includes('right')) {
    windowState.value.width = Math.max(400, resizeStartDims.value.width + dx)
  }
  if (resizeEdge.value?.includes('bottom')) {
    windowState.value.height = Math.max(300, resizeStartDims.value.height + dy)
  }
}

const stopResize = () => {
  isResizing.value = false
  resizeEdge.value = null
  document.removeEventListener('mousemove', onResize)
  document.removeEventListener('mouseup', stopResize)
}

// 处理窗口最大化
const toggleMaximize = () => {
  if (isMaximized.value) {
    // 还原窗口
    if (windowState.value.beforeMaximize) {
      const { x, y, width, height } = windowState.value.beforeMaximize
      windowState.value = { x, y, width, height, beforeMaximize: null }
    }
  } else {
    // 最大化窗口
    windowState.value.beforeMaximize = {
      x: windowState.value.x,
      y: windowState.value.y,
      width: windowState.value.width,
      height: windowState.value.height
    }
    windowState.value.x = 0
    windowState.value.y = 0
    windowState.value.width = window.innerWidth
    windowState.value.height = window.innerHeight
  }
  isMaximized.value = !isMaximized.value
}

// 监听窗口大小变化
const handleWindowResize = () => {
  if (isMaximized.value) {
    windowState.value.width = window.innerWidth
    windowState.value.height = window.innerHeight
  }
}

onMounted(() => {
  window.addEventListener('resize', handleWindowResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleWindowResize)
})

watch(() => props.message, (newMessage) => {
  if (newMessage) {
    content.value = newMessage.content
  }
}, { immediate: true })

watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    // 重置窗口状态
    isMaximized.value = false
    windowState.value = {
      x: window.innerWidth * 0.1,
      y: window.innerHeight * 0.1,
      width: window.innerWidth * 0.8,
      height: window.innerHeight * 0.8,
      beforeMaximize: null
    }
  }
})

const handleSave = () => {
  emit('save', content.value)
  emit('update:modelValue', false)
}

const close = () => {
  emit('update:modelValue', false)
}
</script>

<template>
  <Transition name="fade">
    <div v-if="modelValue" class="fixed inset-0 z-50">
      <!-- 背景遮罩 -->
      <div 
        class="absolute inset-0 bg-black/30 backdrop-blur-sm"
        @click="close"
      ></div>

      <!-- 编辑器窗口 -->
      <div
        ref="dialogRef"
        class="absolute bg-base-100/95 backdrop-blur-sm shadow-xl rounded-lg overflow-hidden"
        :style="dialogStyle"
        :class="{ 'transition-none': isDragging }"
      >
        <!-- 标题栏 -->
        <div 
          class="px-6 py-4 border-b border-base-300/50 flex items-center justify-between bg-base-200/50 cursor-move"
          @mousedown="startDrag"
        >
          <h3 class="font-medium text-base flex items-center gap-2 select-none">
            <i class="ri-edit-line opacity-70"></i>
            编辑消息
          </h3>
          <div class="flex items-center gap-2">
            <button 
              class="btn btn-sm btn-circle btn-ghost hover:bg-base-300/50"
              @click="toggleMaximize"
            >
              <i :class="isMaximized ? 'ri-contract-right-line' : 'ri-expand-right-line'"></i>
            </button>
            <button 
              class="btn btn-sm btn-circle btn-ghost hover:bg-base-300/50"
              @click="close"
            >
              <i class="ri-close-line"></i>
            </button>
          </div>
        </div>
        
        <!-- 编辑区域 -->
        <div class="flex-1 overflow-hidden" :style="{ height: 'calc(100% - 120px)' }">
          <MdEditor
            v-model="content"
            :toolbars="editorConfig.toolbars"
            :toolbarsExclude="editorConfig.toolbarsExclude"
            :preview="editorConfig.preview"
            :language="editorConfig.language"
            class="h-full border-none !bg-transparent"
            previewTheme="github"
            codeTheme="github"
          />
        </div>

        <!-- 底部按钮 -->
        <div class="border-t border-base-300/50 px-6 py-4 bg-base-200/50 flex justify-end gap-2">
          <button 
            class="btn btn-primary btn-sm shadow-sm hover:shadow-md"
            @click="handleSave"
          >
            保存更改
          </button>
          <button 
            class="btn btn-sm shadow-sm hover:shadow-md"
            @click="close"
          >
            取消
          </button>
        </div>

        <!-- 调整大小的手柄 -->
        <div
          v-if="!isMaximized"
          class="absolute bottom-0 right-0 w-4 h-4 cursor-se-resize"
          @mousedown="e => startResize(e, 'bottom-right')"
        ></div>
      </div>
    </div>
  </Transition>
</template>

<style>
/* 自定义 MD Editor 样式 */
.md-editor {
  --md-bk-color: transparent !important;
  --md-border-color: transparent !important;
  --md-color: var(--bc, hsl(var(--bc))) !important;
  --md-hover-color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-dark {
  --md-bk-color: transparent !important;
  --md-border-color: transparent !important;
  --md-color: var(--bc, hsl(var(--bc))) !important;
  --md-hover-color: var(--bc, hsl(var(--bc))) !important;
}

/* 编辑器工具栏样式优化 */
.md-toolbar {
  background-color: var(--md-bk-color) !important;
  border-bottom: 1px solid var(--md-border-color) !important;
  padding: 8px 12px !important;
  min-height: 48px !important;
}

/* 工具栏按钮样式 */
.md-toolbar-item {
  font-size: 1.1rem !important;
  width: 36px !important;
  height: 36px !important;
  margin: 0 2px !important;
  color: var(--md-color) !important;
}

.md-toolbar-item > svg {
  width: 1.2em !important;
  height: 1.2em !important;
}

/* 工具栏下拉菜单样式 */
.md-editor-catalog {
  background-color: var(--b1, hsl(var(--b1))) !important;
  border: 1px solid var(--b3, hsl(var(--b3))) !important;
  border-radius: 0.5rem !important;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
  margin-top: 4px !important;
  padding: 4px !important;
  z-index: 100 !important;
  min-width: 120px !important;
}

.md-editor-catalog button {
  padding: 6px 12px !important;
  width: 100% !important;
  text-align: left !important;
  border-radius: 0.25rem !important;
  color: var(--bc, hsl(var(--bc))) !important;
  display: flex !important;
  align-items: center !important;
  gap: 0.5rem !important;
  font-size: 0.875rem !important;
}

.md-editor-catalog button:hover {
  background-color: var(--b2, hsl(var(--b2))) !important;
}

/* 预览区域样式优化 */
.md-editor-preview {
  background-color: var(--md-bk-color) !important;
  border-left: 1px solid var(--md-border-color) !important;
  padding: 1rem !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

/* 编辑器内容区域样式 */
.md-editor-input {
  padding: 1rem !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-input textarea {
  color: var(--bc, hsl(var(--bc))) !important;
}

/* 标题下拉菜单样式 */
.md-title-dropdown {
  background-color: var(--b1, hsl(var(--b1))) !important;
  border: 1px solid var(--b3, hsl(var(--b3))) !important;
  border-radius: 0.5rem !important;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
  padding: 4px !important;
  z-index: 100 !important;
  min-width: 120px !important;
}

.md-title-dropdown button {
  padding: 6px 12px !important;
  width: 100% !important;
  text-align: left !important;
  border-radius: 0.25rem !important;
  color: var(--bc, hsl(var(--bc))) !important;
  display: flex !important;
  align-items: center !important;
  gap: 0.5rem !important;
  font-size: 0.875rem !important;
}

.md-title-dropdown button:hover {
  background-color: var(--b2, hsl(var(--b2))) !important;
}

/* 预览区域的 Markdown 样式 */
.md-editor-preview {
  font-size: 1rem !important;
  line-height: 1.6 !important;
}

.md-editor-preview h1,
.md-editor-preview h2,
.md-editor-preview h3,
.md-editor-preview h4,
.md-editor-preview h5,
.md-editor-preview h6 {
  color: var(--bc, hsl(var(--bc))) !important;
  margin-top: 1.5em !important;
  margin-bottom: 0.5em !important;
}

.md-editor-preview p {
  color: var(--bc, hsl(var(--bc))) !important;
  margin: 1em 0 !important;
}

.md-editor-preview a {
  color: var(--p, hsl(var(--p))) !important;
  text-decoration: underline !important;
}

.md-editor-preview code {
  background-color: var(--b2, hsl(var(--b2))) !important;
  padding: 0.2em 0.4em !important;
  border-radius: 0.25rem !important;
  font-size: 0.875em !important;
}

.md-editor-preview pre {
  background-color: var(--b2, hsl(var(--b2))) !important;
  padding: 1em !important;
  border-radius: 0.5rem !important;
  overflow-x: auto !important;
}

.md-editor-preview pre code {
  background-color: transparent !important;
  padding: 0 !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-preview blockquote {
  border-left: 4px solid var(--b3, hsl(var(--b3))) !important;
  padding-left: 1em !important;
  margin: 1em 0 !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-preview ul,
.md-editor-preview ol {
  padding-left: 1.5em !important;
  margin: 1em 0 !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-preview table {
  border-collapse: collapse !important;
  width: 100% !important;
  margin: 1em 0 !important;
}

.md-editor-preview th,
.md-editor-preview td {
  border: 1px solid var(--b3, hsl(var(--b3))) !important;
  padding: 0.5em !important;
  color: var(--bc, hsl(var(--bc))) !important;
}

.md-editor-preview th {
  background-color: var(--b2, hsl(var(--b2))) !important;
}

/* 工具栏下拉菜单的图标 */
.md-toolbar-item .md-icon {
  color: var(--bc, hsl(var(--bc))) !important;
}

/* 工具栏分隔符 */
.md-toolbar-divider {
  background-color: var(--b3, hsl(var(--b3))) !important;
}

/* 工具栏提示 */
.md-toolbar-tooltip {
  background-color: var(--b1, hsl(var(--b1))) !important;
  color: var(--bc, hsl(var(--bc))) !important;
  border: 1px solid var(--b3, hsl(var(--b3))) !important;
  padding: 4px 8px !important;
  border-radius: 4px !important;
  font-size: 0.75rem !important;
}
</style>

<style scoped>
/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 窗口动画 */
.modal-enter-active,
.modal-leave-active {
  transition: all 0.3s ease-out;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

/* 优化移动端体验 */
@media (max-width: 768px) {
  .dialog {
    width: 95vw !important;
    height: 90vh !important;
  }
}
</style> 